<template>
  <div class="tranfer-com">
    <div class="tranfer-content">
      <div class="left">
        <div class="title">
          <el-checkbox v-if="showAllSelect" @change="selectAll" v-model="checked">{{ title[0] }}</el-checkbox>
          <span v-else>{{ title[0] }}</span>
        </div>
        <div class="content">
          <div class="transferSearch">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText">
            </el-input>
          </div>

          <el-scrollbar ref="scrollbarLeft" class="transferScrollbar">
            <el-tree
              ref="leftTree"
              :data="data"
              show-checkbox
              :node-key="props.key"
              :filter-node-method="filterNode"
              :default-expand-all="defaultExpandAll"
              :default-expanded-keys="[]"
              :default-checked-keys="defaultCheckedKeys"
              :props="props"
              check-on-click-node
              @check-change="checkChange"
            >
            </el-tree>
          </el-scrollbar>
        </div>
      </div>
      <div class="middle">
        <i class="el-icon-arrow-left"></i>
        <i class="el-icon-arrow-right"></i>
      </div>
      <div class="right">
        <div class="title">
          {{ title[1] }}
          <el-button class="clearBtn" type="text" @click="clearSelect"
            >清空</el-button
          >
        </div>
        <div class="content">
          <div class="transferSearch">
            <el-input placeholder="输入关键字进行过滤" v-model="filterValue" clearable>
            </el-input>
          </div>
          <el-scrollbar ref="scrollbarLeft" class="transferScrollbar">
            <el-tree
              v-if="type == 'tree'"
              ref="rightTree"
              :data="transForm"
              node-key="id"
              :default-expand-all="defaultExpandAll"
              :default-expanded-keys="[]"
              :default-checked-keys="defaultCheckedKeys"
              :props="props"
              :filter-node-method="filterNode"
            >
              <span class="leftItem" slot-scope="{ node, data }">
                <span>{{ data[props.label] }}</span>
                <span>
                  <el-button type="text" size="mini">
                    <i
                      @click.stop="removeKeys(data)"
                      class="el-icon-delete"
                    ></i>
                  </el-button>
                </span>
              </span>
            </el-tree>
            <div class="leftItem" v-for="item in selectList" :key="item.id" v-else>
              <span>{{ item[props.label] }}</span>
              <span>
                <el-button type="text" size="mini">
                  <i @click.stop="removeKeys(item)" class="el-icon-delete"></i>
                </el-button>
              </span>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <div class="footer">
      <el-button @click="cancelSelect">取消</el-button>
      <el-button
        type="primary"
        @click="sureSelect"
        >确定</el-button
      >
    </div>
  </div>
</template>

<script>
export default {
  name: "Transfer",
  props: {
    // 绑定值
    transForm: Array,
    title: {
      type: Array,
      default: () => ["未选择", "已选择"],
    },
    // 类型 tree：树，其它为平铺
    type: {
      type: String,
      default: "tree",
    },
    // 数据源
    data: {
      type: Array,
      default: () => {
        [];
      },
    },
    //  关键值代替集合
    defaultProps: {
      type: Object,
      default: () => {},
    },
    // 默认选中的Key
    defaultCheckedKeys: {
      type: Array,
      default: () => {
        [];
      },
    },
    // 是否默认展开全部
    defaultExpandAll: {
      type: Boolean,
      default: true,
    },
    // 是否开启子集重复校验
    vaildChild: {
      type: Boolean,
      default: false,
    },
    // 当需要校验子项是否重复时，校验的关键字段
    childKey: {
      type: String,
      default: "",
    },
    // 是否开启全选按钮
    showAllSelect: {
      type: Boolean,
      default: true,
    }
  },
  components: {},
  data() {
    return {
      filterText: "", // tree过滤值
      filterValue: "", // 平铺过滤值
      checked: false, // 全选
      parentList: [], // 
      childList: [], // 临时值，存储子项
      selectList: [], // 平铺临时存储值
    };
  },
  computed: {
    props() {
      return Object.assign({
          key: "id",
          children: "children",
          label: "label",
          pid: "parentId",
        }, this.defaultProps)
    }
  },
  watch: {
    filterText(val) {
      console.log(val)
      this.$refs.leftTree.filter(val);
    },
    filterValue(val) {
      if(this.type == 'tree') {
         this.$refs.rightTree.filter(val);
      } else {
         if(val) {
          this.selectList = this.transForm.filter(e => e[this.props.label].includes(val))
         } else {
          this.selectList = this.transForm
         }
      }
    },
    transForm: {
      handler(val) {
        if (!val.length) {
          this.$refs.leftTree.setCheckedNodes([]);
        }
      },
      deep: true,
    },
  },
  created() {},
  mounted() {
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data[this.props.label].indexOf(value) !== -1;
    },
    selectAll() {
      if (this.checked) {
        this.$refs.leftTree.setCheckedNodes(this.data);
        // this.transForm = this.data;
        this.$emit("update:transForm", this.data);
      } else {
        this.$refs.leftTree.setCheckedNodes([]);
        this.selectList = []
        this.$emit("update:transForm", []);
      }
    },
    hasOneof(target, arr, el) {
      return target.some((el) => {
        if(arr.findIndex(e => e.itemCode === el.itemCode) != -1) {
          return true
        }
      });
    },
    checkChange(data, check, bol) {
      if(this.vaildChild && check) {
        this.childList = []
        this.transForm.forEach(e => {
          if(e[this.childKey].length) {
            this.childList= this.childList.concat(e[this.childKey])
          }
        })
       
        if(this.hasOneof(data[this.childKey], this.childList)){
          this.$message({
            type: 'warning',
            message: '子项重复'        
          })
          this.$refs.leftTree.setChecked(data, false, true);
          return false
        }
      }

      if (this.type == "tree") {
        let parentNode = this.$refs.leftTree.getCheckedNodes(false, true);
        let arr = [
          ...this.$refs.leftTree.getHalfCheckedKeys(),
          ...this.$refs.leftTree.getCheckedKeys(),
        ];
        let selectData = JSON.parse(JSON.stringify(parentNode));
        selectData.forEach((e, index) => {
          if (e[this.props.pid] == 0) {
            e.children = this.filterMenu(e.children, arr);
          }
        });
        let tempTransForm = selectData.filter(
          (e) => e[this.props.pid] === 0
        );
        this.selectList = tempTransForm
        this.$emit("update:transForm", tempTransForm);
      } else {
        let tempTransForm = this.$refs.leftTree.getCheckedNodes(true);
        this.selectList = tempTransForm
        this.$emit("update:transForm", tempTransForm);
      }
    },
    filterMenu(menuList, menuCode) {
      return menuList
        .filter((item) => {
          return menuCode.indexOf(item.id) > -1;
        })
        .map((item) => {
          item = Object.assign({}, item);
          if (item.children) {
            item.children = this.filterMenu(item.children, menuCode);
          }
          return item;
        });
    },
    removeKeys(data) {
      this.$refs.leftTree.setChecked(data, false, true);
    },
    addKeys(data){
      this.$refs.leftTree.setChecked(data, true, true);
    },
    cancelSelect() {
      this.filterValue = ''
      this.filterText = ''
      
      this.$emit('cancelSelect')
    },
    sureSelect() {
      this.filterValue = ''
      this.filterText = ''
      this.$emit('sureSelect')
    },
    clearSelect() {
      this.filterValue = ''
      this.filterText = ''
      this.$refs.leftTree.setCheckedNodes([]);
      this.selectList = []
      this.$emit("update:transForm", []);
      this.checked = false;
    },
  },
};
</script>

<style scoped lang='scss'>
.tranfer-com {
  display: inline-block;
  .tranfer-content{
    display: flex;
    align-items: center;
  }
  .footer {
      margin-top: 10px;
      text-align: center;
    }
  .left,
  .right {
    width: 250px;
    border: 1px solid #f5f5f5;
    height: 400px;
    border-radius: 5px;
  }
  .title {
    background-color: #ecf1fa;
    width: 100%;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    box-sizing: border-box;
    text-align: left;
    font-size: 14px;
  }

  .clearBtn {
    float: right;
  }
  .content {
    padding: 10px;
    .transferSearch {
      margin-bottom: 10px;
    }
    .transferScrollbar {
      height: 300px;
      ::v-deep .el-scrollbar__wrap {
        height: 100%;
        overflow: auto;
        width: 100%;
      }
    }
  }
  .middle {
    display: flex;
    flex-direction: column;
    i {
      padding: 10px;
      background-color: dodgerblue;
      color: #fff;
      border-radius: 5px;
      margin: 5px;
    }
  }
  .leftItem {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>